import { reactive } from 'vue'
import { createOID, hasOwnProp } from '../utils/normalUtils'

/**
 *
 */
const injectPool:any = {}

/**
 * 单例容器 生命周期不会销毁
 */
const classPool:any = {}

/**
 *
 * @param name
 * @param state
 */
export function useInjectState(name:string, state:any) {
    if (!hasOwnProp(injectPool, name)) injectPool[name] = reactive(state)
    return injectPool[name]
}

/**
 * 全局单例注入 框架无关
 * @param ClassIns
 */
export function provideClass(ClassIns:any) {
    if (!ClassIns.prototype.__autoId) {
        ClassIns.prototype.__autoId = createOID('class')
        classPool[ClassIns.prototype.__autoId] = new ClassIns()
    }
    return classPool[ClassIns.prototype.__autoId]
}

/**
 * 注入类 框架无关
 * @param classIns
 */
export function injectClass(classIns:any) {
    if (!classIns.prototype.__autoId) provideClass(classIns)
    return classPool[classIns.prototype.__autoId]
}


/**
 * 销毁单例 框架无关
 * @param classIns
 */
export function destroyClass(classIns:any) {
    if (!classIns.prototype.__autoId) return
    const ins = classPool[classIns.prototype.__autoId]
    delete classPool[classIns.prototype.__autoId]
    classIns.prototype.__autoId = undefined
    if (ins.destroy)ins.destroy()
}
